//
//  UIImage+Extension.swift
//  BusinessBao
//
//  Created by Chen on 2017/7/17.
//  Copyright © 2017年 Chen. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
    class func `init`(color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        
        color.setFill()
        UIRectFill(rect)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }


    /// 图片裁剪
    ///
    /// - Parameters:
    ///   - clipSize: 裁剪区域
    ///   - quality: 所需裁剪质量 0-1
    func cropImage(clipSize: CGSize, quality: CGFloat) -> UIImage {
        var q = quality
        if (quality <= 0 || quality > 1) {
            q = 0.9
        }

        var originImage = self
        if (q != 1) {
            let data = UIImageJPEGRepresentation(self, q)
            if (data != nil) {
                originImage = UIImage(data: data!)!
            }
        }

        let sourceImage = originImage;

        let width = originImage.size.width;//图片原始宽
        let height = originImage.size.height;//图片原始高

        let targetWidth = clipSize.width;
        let targetHeight = clipSize.height;
        var scaleFactor: CGFloat = 0;//拉伸比例
        var scaledWidth = targetWidth;//图片需拉伸的宽
        var scaledHeight = targetHeight;//图片需拉伸的高
        var thumbnailPoint = CGPoint(x: 0,y :0);

        if (originImage.size.equalTo(clipSize) == false) {
            let widthFactor = targetWidth / width;
            let heightFactor = targetHeight / height;

            if (widthFactor > heightFactor) {
                scaleFactor = widthFactor; // scale to fit height
            } else {
                scaleFactor = heightFactor; // scale to fit width
            }
            scaledWidth = width * scaleFactor;
            scaledHeight = height * scaleFactor;

            // center the image
            if (widthFactor > heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            } else if (widthFactor < heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }

        //增加屏幕分辨率，保证裁剪后的图片不模糊
        UIGraphicsBeginImageContextWithOptions(clipSize, false, ScreenScale)

        var thumbnailRect = CGRect.zero;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width = scaledWidth;
        thumbnailRect.size.height = scaledHeight;

        sourceImage.draw(in: thumbnailRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!;
    }
}

